<template>
  <div class="flex-column add-migration">
    <div class="flex justify-between align-center title pd-10">
      <span>{{ $t('ADD_MIGRATION_PLAN') }}</span>
      <i class="el-icon-close" style="cursor: pointer;" @click="$emit('close')" />
    </div>
    <div class="flex-1 flex overflow-hidden">
      <add-left
        ref="addLeft"
        :table-list="tableList"
        @getRouteList="getRouteList"
        @goCutover="goCutover"
        @cancel="cancel"
        @connect="connect"
      />
      <add-right ref="addRight" :route-list="routeList" @cutChange="cutChange" />
    </div>
    <plan-detail
      :visible="confirmVisible"
      :plan-data="planData"
      :title="$t('CONFIRM_MIGRATION_PLAN')"
      @save="save"
      @close="confirmVisible = false"
    />
  </div>
</template>
<script>
  import linkMigration from '@/api/oen/LinkMigrationApi'
  import { getParentsById } from '@/utils/common'
  import AddLeft from './AddLeft'
  import AddRight from './AddRight'
  import PlanDetail from './PlanDetail'
  export default {
    components: {
      AddLeft,
      AddRight,
      PlanDetail
    },
    data() {
      return {
        routeList: [],
        tableList: [],
        confirmVisible: false,
        planData: {},
        baseData: {}
      }
    },
    methods: {
      getRouteList(data) {
        this.tableList = []
        this.routeList = []
        linkMigration.linkRecom(data).then(res => {
          this.routeList = res || []
          this.routeList.forEach(i => {
            i.linkId = i.segmentList.map(j => j.id).join('_')
            i.segmentLinkId = i.segmentList
              .map(j => j.startStationId + '_' + (j.cableId || 'no') + '_' + j.endStationId)
              .join('_')
            i.segmentLength = i.segmentList.length
          })
          // 必须保证数据AZ反向正确
          this.routeList.sort((a, b) => {
            return a.segmentLength - b.segmentLength
          })
        })
      },
      goCutover(data) {
        this.$refs.addRight.goCutover(data)
      },
      cutChange(data) {
        this.tableList = data
      },
      cancel() {
        this.tableList = []
        this.routeList = []
        this.$refs.addLeft.formData.aStationId = null
      },
      connect() {
        if (!this.$refs.addRight.$refs.linkTopo) return
        const leftData = this.$refs.addLeft.getSaveData()
        const rightData = this.$refs.addRight.$refs.linkTopo.getSaveData()
        this.baseData = {
          tableList: this.tableList,
          formData: leftData.formData,
          bizData: leftData.bizData,
          curData: rightData.curData,
          removeData: rightData.removeData,
          finalLayout: rightData.finalLayout,
          initTopo: rightData.initTopo
        }
        //         FIBER_MOVE("移纤"),
        // ADD_NOTWORK("新增网段"),
        // PORT_MOVE("端口切换"),
        // DEL_NOTWORK_CHANNEL("删除网段通道")
        //         AUTO("自动"),
        // MANUAL("手动")
        const formData = leftData.formData
        const executePlanList = []
        const rollbackPlanList = []
        this.tableList.forEach(i => {
          const planItem = {
            sourceStationId: i.startStationId,
            sourceNodeId: i.startNodeId,
            sourcePortId: i.startPortId,
            targetStationId: i.endStationId,
            targetNodeId: i.endNodeId,
            targetPortId: i.endPortId
          }
          // AFS移纤
          if (i.startNodeId === i.endNodeId && i.startNode.nodeCategory === 'AFS') {
            const defObject = {
              migrationPlanType: 'FIBER_MOVE',
              migrationOperation: 'AUTO',
              cutover: {
                deviceName: i.startNode.nodeName,
                deviceId: i.startNodeId,
                portId: i.startPortId,
                port: i.startPort,
                connPortId: i.endNodeId,
                connPort: i.endPort
              }
            }
            executePlanList.push({ ...planItem, ...defObject })
            const rollback1 = {
              migrationPlanType: 'FIBER_MOVE',
              migrationOperation: 'AUTO',
              cutover: {
                deviceName: i.startNode.nodeName,
                deviceId: i.startNodeId,
                portId: i.startPortId,
                connPortId: i.startPort.connPortId
              }
            }
            const rollback2 = {
              migrationPlanType: 'FIBER_MOVE',
              migrationOperation: 'AUTO',
              cutover: {
                deviceName: i.startNode.nodeName,
                deviceId: i.endNodeId,
                portId: i.endPortId,
                connPortId: i.endPort.connPortId
              }
            }
            rollbackPlanList.push({ ...rollback1, ...defObject })
            rollbackPlanList.push({ ...rollback2, ...defObject })
          } else {
            // 新增网段
            console.log('segmentChannelList', i)
            const channelItem = {
              startNodeId: i.startNodeId,
              startPortId: i.startPortId,
              startPort: i.startPort,
              startPortCategory: i.startPort.portCategory,
              fiberId: '',
              endNodeId: i.endNodeId,
              endPortId: i.endPortId,
              endPort: i.endPort,
              endPortCategory: i.endPort.portCategory
            }
            const executeData = executePlanList.find(
              j =>
                j.networkSegment &&
                ((j.networkSegment.startNodeId === channelItem.startNodeId &&
                  j.networkSegment.endNodeId === channelItem.endNodeId) ||
                  (j.networkSegment.startNodeId === channelItem.endNodeId &&
                    j.networkSegment.endNodeId === channelItem.startNodeId))
            )
            if (executeData) {
              console.log('executeData', executeData)

              if (
                executeData.networkSegment.startNodeId === channelItem.startNodeId &&
                executeData.networkSegment.endNodeId === channelItem.endNodeId
              ) {
                executeData.networkSegment.segmentChannelList.push(channelItem)
              } else {
                const newChannelData = {
                  startNodeId: channelItem.endNodeId,
                  startPortId: channelItem.endPortId,
                  startPort: channelItem.endPort,
                  startPortCategory: channelItem.endPort.portCategory,
                  fiberId: '',
                  endNodeId: channelItem.startNodeId,
                  endPortId: channelItem.startPortId,
                  endPort: channelItem.startPort,
                  endPortCategory: channelItem.startPort.portCategory
                }
                executeData.networkSegment.segmentChannelList.push(newChannelData)
              }
              return
            }
            const defObject = {
              migrationPlanType: 'ADD_NOTWORK',
              migrationOperation: 'MANUAL',
              networkSegment: {
                ...i,
                id: '',
                startNodeCategory: i.startNode.nodeCategory,
                endNodeCategory: i.endNode.nodeCategory,
                segmentName:
                  this.getRegionName(i.startStationId) +
                  '/' +
                  i.startNode.nodeName +
                  '-' +
                  this.getRegionName(i.endStationId) +
                  '/' +
                  i.endPort.nodeName,
                cable: {},
                cableId: '',
                cableLength: '',
                segmentChannelList: [channelItem]
              }
            }
            executePlanList.push({ ...planItem, ...defObject })
            rollbackPlanList.push({
              ...planItem,
              ...defObject,
              migrationPlanType: 'DEL_NOTWORK_CHANNEL'
            })
          }
        })
        // 删除网段通道
        rightData.removeData.forEach(i => {
          console.log('remove', i)
          if (i.startNodeId === i.endNodeId) return
          const planItem = {
            migrationPlanType: 'DEL_NOTWORK_CHANNEL',
            migrationOperation: 'AUTO',
            segmentChannelId: i.channelId,
            sourceStationId: i.startStationId,
            sourceNodeId: i.startNodeId,
            sourceNode: i.startNode,
            sourcePortId: i.startPortId,
            sourcePort: i.startPort,
            targetStationId: i.endStationId,
            targetNodeId: i.endNodeId,
            targetNode: i.endNode,
            targetPortId: i.endPortId,
            targetPort: i.endPort
          }
          executePlanList.push(planItem)
          const rollback = {
            migrationPlanType: 'ADD_NOTWORK',
            migrationOperation: 'MANUAL',
            networkSegment: {
              ...i,
              id: '',
              startNodeCategory: i.startNode.nodeCategory,
              endNodeCategory: i.endNode.nodeCategory,
              segmentName:
                this.getRegionName(i.startStationId) +
                '/' +
                i.startNode.nodeName +
                '-' +
                this.getRegionName(i.endStationId) +
                '/' +
                i.endPort.nodeName,
              cable: {},
              cableId: '',
              cableLength: '',
              segmentChannelList: [{ ...i, id: '' }]
            }
          }
          rollbackPlanList.push(rollback)
        })
        this.planData = {
          bizId: leftData.bizData ? leftData.bizData.bizId : '',
          bizOpen: leftData.bizData || null,
          startStationId: formData.aStationId,
          startNodeId: formData.aNodeId,
          startNode: formData.aNodeData,
          startPortId: formData.aPortId,
          startPort: formData.aPortData,
          endStationId: formData.zStationId,
          endNodeId: formData.zNodeId,
          endNode: formData.zNodeData,
          endPortId: formData.zPortId,
          endPort: formData.zPortData,
          executePlanList: executePlanList,
          rollbackPlanList: rollbackPlanList,
          finalLayout: rightData.finalLayout,
          initTopo: rightData.initTopo
        }
        console.log('this.planData ', this.planData)
        this.confirmVisible = true
      },
      save(data) {
        const queryData = {
          ...this.planData,
          ...data
        }
        console.log('queryData', queryData)
        delete queryData.bizOpen
        linkMigration
          .add(queryData)
          .then(res => {
            this.$message.success('ADD_SUCCESS')
            this.$emit('close')
          })
          .catch(() => {
            this.$message.error('ADD_FAILED')
          })
      },
      // 查询区域、站点名
      getRegionName(regionId) {
        const regionList = (getParentsById(this.regionTree, regionId, 'regionId') || [])
          .reverse()
          .map(i => i.regionName)
        return regionList.join('/')
      }
    }
  }
</script>
<style lang="scss">
  @import '@/assets/css/mixin.module.scss';

  .add-migration {
    .title {
      margin-bottom: 10px;
      font-weight: bold;
      @include themeify {
        color: themed('textColor');
      }
      & > i {
        font-size: 30px;
      }
    }
  }
</style>
